package com.ft.oa.service.customer.impl;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.conditions.update.LambdaUpdateChainWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.ft.oa.domain.customer.Customer;
import com.ft.oa.domain.dto.knowledgeBase.AttachmentDto;
import com.ft.oa.domain.industrys.Industry;
import com.ft.oa.enums.DirectoryTypeEnum;
import com.ft.oa.enums.ManagerEnum;
import com.ft.oa.mapper.customer.CustomerMapper;
import com.ft.oa.mapper.industrysMapper.IndustryMapper;
import com.ft.oa.service.customer.CustomerService;
import com.ft.oa.service.knowledgeBase.DirectoryService;
import com.ft.oa.service.project.ExecProjectService;
import com.ft.oa.utils.SecurityUtils;
import com.ft.oa.web.customer.rq.CustomerPage;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.time.LocalDateTime;
import java.util.Date;
import java.util.List;

@Service
public class CustomerServiceImpl implements CustomerService {

    @Resource
    private CustomerMapper customerMapper;

    @Resource
    private ExecProjectService execProjectService;

    @Resource
    private DirectoryService directoryService;

    @Resource
    private IndustryMapper industryMapper;

    /**
     * 根据条件查询企业
     */
    @Override
    public IPage<Customer> selectCustomerById(CustomerPage customerPage) {
        IPage<Customer> page = new Page<>(customerPage.getPage(),customerPage.getSize());
        QueryWrapper<Customer> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("state",0);
        if (customerPage.getName()!=null&& !"".equals(customerPage.getName())){
            queryWrapper.like("name",customerPage.getName());
        }
        if(ManagerEnum.GENERAL.toString().equals(SecurityUtils.getCurrentUser().getManager())){
            queryWrapper.eq("creator",SecurityUtils.getCurrentUser().getId());
        }
        queryWrapper.select().orderByDesc("update_time");
        IPage<Customer> customerIPage = customerMapper.selectPage(page, queryWrapper);
        customerIPage.getRecords().forEach(e->{
            int listBySql = execProjectService.getListBySql(e.getId().longValue());
            e.setProjectCount(listBySql);
            if(e.getAchment() != null){
                e.setAttachments(JSONObject.parseArray(e.getAchment(), AttachmentDto.class));
            }
        });
        return  customerIPage;
    }

    /**
     * 添加企业客户信息
     * @param customer
     * @return
     */
    @Override
    public int insertCustomer(Customer customer) {
        List<AttachmentDto> attachments = customer.getAttachments();
        if (attachments != null&&attachments.size()>0){
            String jsonString = JSONArray.toJSONString(attachments);
            customer.setAchment(jsonString);
        }
        Industry industry = industryMapper.selectById(customer.getIndustryId());
        customer.setHyname(industry.getHyname());
        Date date = new Date();
        customer.setCreatorTime(date);
        customer.setUpdateTime(LocalDateTime.now());
        customer.setRecord(0);//第一次新增初始拜访次数0
        customer.setHeadCount(0);//第一次增加初始化公司人员
        int insert = customerMapper.insert(customer);
        /**
         * 保存附件项目相关的公共方法
         *
         * @param attachments 附件集合
         * @param source      来源  根据 DirectoryTypeEnum
         * @param relationId  业务id
         * @param sourceId    如果一个表单有多个附件，用于标识附件属于表单的哪个附件
         * @param  projectNumber 项目编号  全局同一
         */
        directoryService.saveProAttachment(attachments,DirectoryTypeEnum.FILING_CUSTOMERFILE.getCode(),String.valueOf(customer.getId()),"1","null");
        return insert;
    }

    /**
     * 修改企业客户信息
     * @param customer
     * @return
     */
    @Override
    public int updateCustomer(Customer customer) {
        if (customer != null) {
            Industry industry = industryMapper.selectById(customer.getIndustryId());
            customer.setHyname(industry.getHyname());
            customer.setUpdateTime(LocalDateTime.now());
            List<AttachmentDto> attachments = customer.getAttachments();
            if (attachments != null && attachments.size() > 0) {
                String jsonString = JSONArray.toJSONString(attachments);
                customer.setAchment(jsonString);
            }
            /**
             * 保存附件项目相关的公共方法
             *
             * @param attachments 附件集合
             * @param source      来源  根据 DirectoryTypeEnum
             * @param relationId  业务id
             * @param sourceId    如果一个表单有多个附件，用于标识附件属于表单的哪个附件
             * @param  projectNumber 项目编号  全局同一
             */
            directoryService.saveProAttachment(attachments,DirectoryTypeEnum.FILING_CUSTOMERFILE.getCode(),String.valueOf(customer.getId()),"1","null");
            return customerMapper.updateById(customer);
        }
        return 0;
    }

    /**
     * 删除企业客户信息
     * @param id
     * @return
     */
    @Override
    public int deleteCustomer(Integer id) {
        LambdaUpdateChainWrapper<Customer> wrapper=new LambdaUpdateChainWrapper<>(customerMapper);
        wrapper.eq(Customer::getId,id)
                .set(Customer::getState,1)
                .set(Customer::getUpdateTime,LocalDateTime.now())
                .update();
        return 0;
    }

    /**
     * 查询所有公司
     * @return
     */
    @Override
    public List<Customer> selectCustomer() {
        QueryWrapper<Customer> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("state",0);
        queryWrapper.select("name","id");
        return customerMapper.selectList(queryWrapper);
    }

}
